var _global = require('global/global.js');
var _Scene = require('component/scene.js');
var _layout = require('tools/layout.js');
var _relative = _layout.relative;
var _inherit = require('core/inherit.js');
var _TouchNode = require('event/touchnode.js').TouchNode;

//var _GC = require('nativeclasses').gcobserver;
var S = require('res/style.js');

var TWEEN = require('third_party/tweenjs/tween.js');
var _Messages = require('config/messages.js');

var _Record = require('./menu/record.js');
var _Segment = require('./menu/segment.js');
var _SlideView = require('./menu/slideview.js');

var _Pane = require('scenes/widget/pane.js');
var _Title = require('./menu/title.js');
var _Constance = require('./menu/constance.js');
var _Delegates = require('./menu/delegates.js');
var _SlideDelegate = require('./menu/slidedelegate.js');
var _BackListener = require('global/backlistener.js');

var _ReuseScore = require('./menu/reusescore.js');

// ==========================
// Menu
// ==========================
var Menu = _Scene.createScene(
    function (records, retry) {
        this.setId('menu');

        this.mLocal = _Constance.getLocal();
        this.mLocal.add('retry', retry || false);
        this.mLocal.add('scroll', _Constance.SCROLL_NONE);
        this.mLocal.add('scene.menu', this);// instance can not retain this
        this.initTitles();

        var screen = _global.screen;
        var w = screen.width(), h = screen.height();

        // title
        this.mHeader = new _Pane();

        // reuse
        this.mLocal.add('instance.reuse_score', new _ReuseScore());

        // slide
        this.addChild(this.mSlide = new _SlideView());
        this.loadRecords(records);
        this.loadStatistics();
        this.mSlide.setup();

        // scroll to first view
        var piece;
        if (records.length > 0) {
            piece = this.mSlide.getPiece(records.length - 1);
            this.displayTitle(piece);
        } else {
            piece = this.mSlide.getPiece(0);
            this.displayTitle(piece);
        }

        var slidetouch = new _SlideDelegate(this, this.mSlide, piece);
        var delegates = new _Delegates(slidetouch, this.mLocal.find('touch.statistics'));
        this.mLocal.add('touch.delegates', delegates);
        this.getEventNode().setDelegate(delegates);

        // add later
        this.addChild(this.mHeader);
        this.onSizeChange(w, h);
    }
);
Menu.prototype.onTitleFinishShowing = function (title) {
    this.mHeader.findFragment(title.getId()).remove();
};
Menu.prototype.initTitles = function () {
    var hall = _Title.textTitle('Hall of Records');
    hall.setId('instance.title_statis');
    hall.on('finishshowing', this.onTitleFinishShowing, this);
    var wrap = _Title.wrap(hall);
    wrap.setId('instance.title_statis');

    var record = _Title.buttonTitle();
    record.setId('instance.title_record');
    record.on('finishshowing', this.onTitleFinishShowing, this);

    this.mLocal.add('title_statis', hall);
    this.mLocal.add('instance.title_record', record);
    this.mLocal.add('instance.title_statis', wrap);
};
Menu.prototype.toJSON = function () {
    return this.toString();
};
Menu.prototype.onSizeChange = function (w, h) {
    this.setSize(w, h);

    this.mSlide.resize(w, h);
    this.mHeader.setSize(_Constance.titleSize);
    _relative.local.layoutTo(this.mHeader, 0.5, 1, this, 0.5, 1);
};
Menu.prototype.createTitle = function (piece) {
    if (piece.getId() == 'record') {
        return this.mLocal.find('instance.title_record');
    } else {
        return this.mLocal.find('instance.title_statis');
    }
};
/**
 * display immediately
 * @param piece
 */
Menu.prototype.displayTitle = function (piece) {
    this.mHeader.dumpFragments();
    this.mHeader.addFragment(this.createTitle(piece));
};
/**
 * display with fadein and fade out
 * @param piece
 */
Menu.prototype.showTitle = function (piece) {
    this.mHeader.forEach(function (fragment) {
        fragment.getView().fadeOut();
    });

    var next = this.createTitle(piece);
    next.fadeIn();
    this.mHeader.addFragment(next);
};
Menu.prototype.update = function (context) {
};
/**
 * unbind local data
 * @param context
 */
Menu.prototype.release = function (context) {
};

// ----------------
Menu.prototype.loadStatistics = function () {
    this.mSlide.addSegment(new _Segment('statis', module.$('./menu/statistics.js'), 150, 420));
};
/**
 * load history records
 * @param records
 */
Menu.prototype.loadRecords = function (records) {
    var rs = [];
    for (var i = records.length - 1; i > -1; i--) {
        rs.push(new _Record(records[i]));
    }
    this.mSlide.addSegment(new _Segment('record', rs, 160, 400));
};

Menu.prototype.onButtonClick = function (button) {
    _global.cancelEvents();
    switch (button.getId()) {
        case 'retry':
            this.goBack(require('scenes/game.js').newInstance());
            break;
        case 'back':
            this.goBack(this.mLocal.find('instance.from'));
            break;
        case 'share':
            _Messages.share();
            break;
    }
};
Menu.prototype.recoverFromLostContext = function (context) {
    _Scene.prototype.recoverFromLostContext.call(this, context);

    // make sure local variable is recovered
    var instance = this.mLocal.find('instance');
    for (var i in instance) {
        if (instance[i] !== this) {
            instance[i].recoverFromLostContext(context);
        }
    }
};
Menu.prototype.onEnter = function () {
    _BackListener.bindScene(this);
};
// ---------------- exist
Menu.prototype.goBack = function (previous) {
    this.mLocal.release();
    require('scenes/widget/sceneanima.js')
        .createAnima(this, previous)
        .direction('down')
        .gcOnStart(false)
        .start();

};
Menu.prototype.onBackPressed = function () {
    if (this.mLocal.find('retry')) {
        this.mLocal.release();
        require('scenes/cover.js').newInstance().showCover(this);
    } else {
        this.goBack(this.mLocal.find('instance.from'));
    }
};

/**
 * @param current current scene
 */
Menu.prototype.showMenu = function (current) {
    var screen = _global.screen;
    this.onSizeChange(screen.width(), screen.height());

    // if not retry, keep refer to current scene
    if (!this.mLocal.find('retry')) {
        this.mLocal.add('instance.from', current);
    }

    require('scenes/widget/sceneanima.js')
        .createAnima(current, this)
        .direction('up')
        .gcOnStart(false)
        .start();
};

// ---------------- touch
Menu.prototype.createEventNode = function () {
    return new _TouchNode(this);
};
Menu.prototype.onTouch = function (event) {
    return false;
};


module.exports = Menu;